package com.mark.util;

import java.io.*;
import java.net.URL;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.helpers.Loader;



/**
 * 读取application.properties 配置文件
 * @author wust
 *
 */
public class ConfigManager {
	
	static Logger log = Logger.getLogger(ConfigManager.class);
	
	private static ConfigManager m_instance;
	private static String PFILE;

	public static String getAppGateIP(){
		if( m_instance == null ){
			return ConfigManager.getInstance().getConfigItem("YUNGATEIP", "192.16.16.82").toString();
		}else{
			return m_instance.getConfigItem("YUNGATEIP", "192.16.16.82").toString();
		}
	}
	public static Integer getAppGatePort(){
		if( m_instance == null ){
			return Integer.parseInt( ConfigManager.getInstance().getConfigItem("YNGATEPORT", "192.16.16.82").toString() );
		}else{
			return Integer.parseInt( m_instance.getConfigItem("YNGATEPORT", "192.16.16.82").toString() );
		}
	}
	
	synchronized public static ConfigManager getInstance() {
		if (m_instance == null) {
			if (PFILE == null) {
				URL url = Loader.getResource("wx.properties");
				PFILE = url.getPath();
				PFILE = PFILE.replaceAll("%20", " ");
			}
			m_instance = new ConfigManager();
		}
		return m_instance;
	}

	private File m_file = null;
	private long m_lastModifiedTime = 0;
	private Properties m_props = null;

	private ConfigManager() {
		m_file = new File(PFILE);
		m_lastModifiedTime = m_file.lastModified();

//		if (m_lastModifiedTime == 0) {
//			System.err.println(PFILE + " file does not exist!");
//		}

		m_props = new Properties();

		try {
			m_props.load(new FileInputStream(PFILE));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("加载资源文件["+PFILE+"]出错!");
		}
	}

	/**
	 * 获取application.properties资源文件中配置值
	 * @param name
	 * @param defaultVal
	 * @return
	 */
	final public Object getConfigItem(String name, Object defaultVal) {
		long newTime = m_file.lastModified();
		if (newTime == 0) {
			if (m_lastModifiedTime == 0) {
				log.error("加载资源文件["+PFILE+"]出错." + " file does not exist!");
			} else {
				log.error("加载资源文件["+PFILE+"]出错." + " file was deleted!!");
			}
			return defaultVal;
		} else if (newTime > m_lastModifiedTime) {
			m_props.clear();
			try {
				m_props.load(new FileInputStream(PFILE));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		m_lastModifiedTime = newTime;

		Object val = m_props.getProperty(name);
		if (val == null) {
			return defaultVal;
		} else {
			return val;
		}
	}
	
	public static String getString(String strKey, String defaultVal){
		if( m_instance == null ){
			return ConfigManager.getInstance().getConfigItem(strKey, defaultVal).toString();
		}else{
			return m_instance.getConfigItem(strKey, defaultVal).toString();
		}
	}

	/**
	 * 更新（或插入）一对properties信息(主键及其键值)
	 * 如果该主键已经存在，更新该主键的值；
	 * 如果该主键不存在，则插件一对键值。
	 * @param keyname 键名
	 * @param keyvalue 键值
	 */
	public static boolean writeProperties(String keyname,String keyvalue,String profilepath) {
		boolean flag = false;
		Properties properties = new Properties();
		try {
			// 调用 Hashtable 的方法 put，使用 getProperty 方法提供并行性。
			// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
			if(null==profilepath||profilepath.trim().length()==0){
				URL url = Loader.getResource("wx.properties");
				profilepath = url.getPath();
			}
			properties.load(new FileInputStream(profilepath));
			OutputStream fos = new FileOutputStream(profilepath);
			properties.setProperty(keyname, keyvalue);
			// 以适合使用 load 方法加载到 Properties 表中的格式，
			// 将此 Properties 表中的属性列表（键和元素对）写入输出流
			properties.store(fos, "Update '" + keyname + "' value");
		}catch (FileNotFoundException fileException){
			log.error("文件未找到，请确认路径或读写权限");
		} catch (IOException ioException) {
			log.error("文件更新错误,错误原因："+ioException.getMessage());
		}
		flag = true;
		return flag;
	}
	
}